<template>
  <div id="app">
    <div class="todo-container">
      <div class="todo-wrap"> 
        <Header />
        <List :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"/>
        <Footer :todos="todos" :selectAll="selectAll" :clearCheckTodos="clearCheckTodos"/>
      </div>
    </div>
    <hr>
    <TodoList :todos="todos">
      <template v-slot="scoped">
        <span :style="{color:scoped.todo.completed ? 'green' : ''}">{{scoped.todo.title}}</span>
      </template>
    </TodoList>
    <hr>
    <TodoList :todos="todos">
      <template v-slot="{todo,index}">
        <span :style="{color:index%2===1 ? 'green' : 'blue'}">{{todo.title}}</span>
      </template>
    </TodoList>
  </div>
</template>

<script>
import Header from './components/Header.vue'
import List from './components/List.vue'
import Footer from './components/Footer.vue'
import {nanoid} from 'nanoid'
import TodoList from './test/TodoList.vue'

export default {
  name: 'App',
  data(){
    return{
      // 初始时就读取json数据，并解析为js数数组，如果没有指定就是空数组
      todos:[]
    }
  },
  mounted(){
    // 模拟异步加载得到todos数据
    setTimeout(()=>{
      this.todos = JSON.parse(localStorage.getItem('todos_key')) || [];
    },2000)
    this.$globaleventBus.$on('addTodo',this.addTodo);
    this.$globaleventBus.$on('deleteTodo',this.deleteTodo);
  },
  // 监视todos的变化
  watch:{
    todos:{
      handler(value){
        // 将todos保存在local Storage中（必须保存为JSON格式）
        localStorage.setItem('todos_key',JSON.stringify(value))
      },
      deep:true,//深度监视，数组内部的对象数据发生变化的时候就会触发
    }
  },
  methods:{
    // 添加一个todo
    addTodo(todo){
      todo.id = nanoid();
      this.todos.push(todo);
    },
    // 改变勾选状态的函数
    checkTodo(todo){
      todo.completed =!todo.completed;
    },
    // 删除一个todo
    deleteTodo(index){
      this.todos.splice(index,1);
    },
    // 是否全选
    selectAll(isCheck){
     this.todos.forEach(todo=>todo.completed = isCheck);
    },
    // 清除所有选中的
    clearCheckTodos(){
      this.todos = this.todos.filter(todo=>!todo.completed);
    }
  },
  components: {
    Header,
    List,
    Footer,
    TodoList
  }
}
</script>

<style>
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>
